# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：    wechat_notifier.py
   Description:   企业级企业微信通知工具类，支持发送文本和Markdown格式消息
-------------------------------------------------
"""

from __future__ import annotations

import requests
import json
import logging
from typing import List, Dict, Any
from pydantic import BaseModel, Field, ValidationError

# 初始化日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


class WeComConfig(BaseModel):
    webhook_url: str = Field(..., description="企业微信群机器人Webhook URL")


class WeComNotifier:
    """
    企业级企业微信通知工具类，支持发送文本和Markdown消息。
    """

    def __init__(self, config: WeComConfig):
        self.webhook_url = config.webhook_url

    def send_text_message(self, content: str, mentioned_list: List[str] = None) -> Dict[str, Any]:
        """
        发送文本消息
        :param content: 消息内容
        :param mentioned_list: 需要@的成员的微信账号列表
        :return: 企业微信接口的响应结果
        """
        message = {
            "msgtype": "text",
            "text": {
                "content": content,
                "mentioned_list": mentioned_list if mentioned_list else []
            }
        }
        return self._send_message(message)

    def send_markdown_message(self, content: str) -> Dict[str, Any]:
        """
        发送Markdown消息
        :param content: Markdown格式的消息内容
        :return: 企业微信接口的响应结果
        """
        message = {
            "msgtype": "markdown",
            "markdown": {
                "content": content
            }
        }
        return self._send_message(message)

    def _send_message(self, message: Dict[str, Any]) -> Dict[str, Any]:
        """
        发送消息到企业微信群
        :param message: 消息内容字典
        :return: 企业微信接口的响应结果
        """
        headers = {
            'Content-Type': 'application/json'
        }
        try:
            response = requests.post(self.webhook_url, headers=headers, data=json.dumps(message))
            response.raise_for_status()
            result = response.json()
            if result.get("errcode") != 0:
                logger.error(f"发送企业微信消息失败: {result}")
            else:
                logger.info(f"企业微信消息发送成功: {result}")
            return result
        except requests.exceptions.RequestException as e:
            logger.error(f"企业微信消息发送失败，错误信息: {e}")
            return {"errcode": -1, "errmsg": str(e)}


# 示例使用
if __name__ == '__main__':
    # 初始化企业微信配置
    try:
        config = WeComConfig(
            webhook_url="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_WEBHOOK_KEY"
        )
    except ValidationError as e:
        logger.error(f"配置校验失败: {e}")
        raise

    notifier = WeComNotifier(config)
    # 发送文本消息
    notifier.send_text_message("测试用例执行成功！", mentioned_list=["@all"])
    # 发送Markdown消息
    markdown_content = """
    ### 测试报告
    **测试结果**: 所有测试用例已成功通过。
    [点击查看详细报告](https://example.com/report)
    """
    notifier.send_markdown_message(markdown_content)
